import '../assets/css/UsserInfo/userinfo.less'
import { Button, Flex, Form, Input, Pagination, Popconfirm, Table, message, type TableProps, Cascader } from "antd";
import { userinfoDel, userinfoDelAll, userinfoList,buildingList, userinfoUpdateState } from '../apis/userinfo'
import { useEffect, useState } from "react";
import { Image } from 'antd';
import type { UserInfoParams, UserList, buildingTypeList } from "../type/userinfo";
import EAUserInfo from '../component/userinfo/UserInfoEA';
import dayjs from 'dayjs';
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

function Userinfo() {
    const [params, setParams] = useState<UserInfoParams>({ usertype: '', buildingid: 0, name: '', houseno: '', mobile: '', psize: 10, page: 1 })
    const [tableData, setTableData] = useState<UserList[]>([])

    const getUserInfoList = async () => {
        const res = await userinfoList(params);
        setTableData(res.data.list);
        setTotal(res.data.counts)
    }
    
    const getBuildingList = async () => {
        const res = await buildingList();
        setBuilding(res.data.list)
    }
    const [building,setBuilding]=useState<buildingTypeList[]>()
    useEffect(() => {
        getUserInfoList()
    }, [params])
    useEffect(() => {
        getBuildingList()
    }, [])
    const [total, setTotal] = useState<number>(0)
    const onChange = (page: number, psize: number) => {
        setParams({ ...params, page, psize })
    }
    // 删除
    const delOne = async (id: number) => {
        const res = await userinfoDel(id)
        if (res.errCode === 10000) {
            message.success('删除成功')
            getUserInfoList()
        } else {
            message.success('删除失败')
        }
    }
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
        },
        {
            title: '头像',
            dataIndex: 'photo',
            width: 110,
            render: (text: string) => (
                <Image height={30} width={30} src={text ? import.meta.env.VITE_IMG_URL + text : 'error'}
                />
            ),
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            render: (text: number) => (
                <>
                    {text === 1 ? '男' : '女'}
                </>
            )
        },
        {
            title: '类型',
            dataIndex: 'usertypeName',

        },
        {
            title: '证件',
            dataIndex: 'cardid',

        },
        {
            title: '电话',
            dataIndex: 'mobile',

        },
        {
            title: '籍贯',
            dataIndex: 'usernative',
        },
        {
            title: '民族',
            dataIndex: 'nation',

        },
        {
            title: '房间号',
            dataIndex: 'houseno',
        },
        {
            title: '审核状态',
            dataIndex: 'memberid',
            render: (text: number) => <div>{text==0?'已审核':'未审核'}</div>,
        },
        {
            title: '添加时间',
            dataIndex: 'addtime',
            render: (text: string) => <div>{dayjs(text).format('YYYY-MM-DD HH:mm')}</div>,
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 200,
            render: (value: number, record: UserList) => (
                <Flex gap={10}>
                    <Button color="green" onClick={()=>{setEditUserInfo(record),setIsUserModalOpen(true)}} variant="solid">修改</Button>
                    <Popconfirm
                        title="确定要删除这个吗"
                        onConfirm={() => { delOne(value) }}
                        okText="是"
                        cancelText="否"
                    ><Button type="primary" danger>删除</Button></Popconfirm>
                </Flex>
            )
        }
    ];
    // 添加居民
    const [isUserModalOpen, setIsUserModalOpen] = useState(false);  //添加居民
    // 修改的居民参数
    const [editUserInfo, setEditUserInfo] = useState<UserList | undefined>();  //修改的居民信息
    // 多选框
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [ids,setIds]=useState<any[]>([])
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
        setIds(newSelectedRowKeys)
    };
    const rowSelection: TableRowSelection<UserList> = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    // 确认提交
    const onFinish = (values: UserInfoParams) => {
        setParams({ ...params, ...values, page: 1 });
    }
    // 取消弹窗
    const cancelHandle=()=>{
        setIsUserModalOpen(false)
        setEditUserInfo(undefined);
    }
    // 多个删除
    const onDelAll= async ()=>{
        await userinfoDelAll({ids})
        await getUserInfoList()
    }

    // 多个审核
    const onUpdateState=async ()=>{
        await userinfoUpdateState({ids,state:2})
        await getUserInfoList()
    }
    return (
        <Flex vertical gap={20}>
            {
                isUserModalOpen && <EAUserInfo editUserInfo={editUserInfo!} onCancel={cancelHandle} building={building!} getUserInfoList={getUserInfoList}></EAUserInfo>
            }
            <div className="hecad">
                <h3>居民管理</h3>
            </div>
            <Form layout="inline" onFinish={onFinish}>
                <Form.Item<UserInfoParams> name="buildingid" label="楼栋" rules={[{ required: true, message: '请选择楼栋' }]}>
                    <Cascader allowClear fieldNames={{label:'name',value:'id'}} options={building} placeholder="选择小区" />
                </Form.Item>
                <Form.Item<UserInfoParams> label="姓名" name="name">
                    <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item<UserInfoParams> label="电话" name="mobile">
                    <Input placeholder="请输入电话" />
                </Form.Item>
                <Form.Item<UserInfoParams> label="房间号" name="houseno">
                    <Input placeholder="请输入房间号" />
                </Form.Item>
                <Form.Item label="">
                    <Button type="primary" htmlType="submit">查询</Button>
                </Form.Item>
            </Form>
            <Flex gap={10} style={{ marginTop: '20px', marginBottom: '20px' }}>
                <Button style={{ marginLeft: '10px' }} onClick={()=>{setIsUserModalOpen(true)}} type="primary">添加</Button>
                <Popconfirm
                        title="确定要删除这个吗"
                        onConfirm={() => { onDelAll() }}
                        okText="是"
                        cancelText="否"
                    ><Button style={{ marginLeft: '10px' }} danger type="primary">批量删除</Button>
                    </Popconfirm>

                <Button style={{ marginLeft: '10px' }} onClick={()=>onUpdateState()} color="green" variant="solid">批量审核</Button>
            </Flex>

            <Table rowKey='id' dataSource={tableData} pagination={false} rowSelection={rowSelection} style={{ width: '100%' }} columns={columns} />

            <Flex justify="center">
                {<Pagination onChange={onChange} total={total} showTotal={(total) => `共 ${total} 条`} current={params.page} pageSizeOptions={['5', '10', '15', '25']} />}
            </Flex>
        </Flex>
    )
}

export default Userinfo